const Koa = require("koa");

const app = new Koa();

const USER_ISLOGIN = "USER_ISLOGIN";

app.use((ctx, next) => {
  const isLogin = false;
  if (!isLogin) {
    ctx.app.emit("error", new Error(USER_ISLOGIN), ctx);
  }
});

app.on("error", (err, ctx) => {
  let status = 400;
  let message = "";

  switch (err.message) {
    case USER_ISLOGIN:
      status = 401;
      message = "您还没有登录";
      break;
    default:
      message = "没有找到";
  }
  ctx.status = status;
  ctx.body = message;
});

app.listen(8000, () => {
  console.log("Koa错误处理服务器启动成功");
});
